package cn.kgc.javaweb.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author: mosin
 * @version: v1.0  2022/5/24
 * 请求分发   方式2  利用反射
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //获取方法名
        String method = req.getParameter("method");
        //获取类对象
        Class clazz = this.getClass();
        //通过方法名 获取方法对象
        try {
            Method declaredMethod = clazz.getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class);
           //设置权限
            declaredMethod.setAccessible(true);
            // 调用方法
            declaredMethod.invoke(this, req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
